#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFileDialog>
#include <QDebug>

QPlainTextEdit *outputPlainText = nullptr;

int luaPrint(lua_State *L)
{
    int nargs = lua_gettop(L);
    QString result;

    for (int i = 1; i <= nargs; i++) {
        if (lua_isstring(L, i)) {
            result += lua_tostring(L, i);
        } else {
            result += luaL_tolstring(L, i, nullptr);
            lua_pop(L, 1); // 移除 luaL_tolstring 压入栈的结果
        }
        if (i < nargs) {
            result += "\t";
        }
    }

    //result += "\n";

    outputPlainText->appendPlainText(result);

    return 0;
}

// 不定参数函数
int myVarArgFunction(lua_State* L) {

    // 获取参数的数量
    int numArgs = lua_gettop(L);

    // 遍历并打印所有参数
    for (int i = 1; i <= numArgs; ++i) {
        if (lua_isnumber(L, i)) {
            qDebug() << "Argument " << i << ": " << lua_tonumber(L, i);
        } else if (lua_isstring(L, i)) {
            qDebug() << "Argument " << i << ": " << lua_tostring(L, i);
        } else {
            qDebug() << "Argument " << i << ": [Unknown type]";
        }
    }

    // 遍历并打印所有参数
    QString cmdline;
    for (int i = 1; i <= numArgs; ++i) {
        if (lua_isstring(L, i)) {
            qDebug() << "Argument " << i << ": " << lua_tostring(L, i);
            cmdline += lua_tostring(L, i);
            cmdline += " ";
        } else {
            qDebug() << "Argument " << i << ": [Unknown type]";
        }
    }
    qDebug() << "cmdline: " << cmdline;

    // 返回结果个数
    return 0;
}

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    outputPlainText = ui->plainTextEditOutput;

    //create lua
    L = luaL_newstate();

    // 打开所有标准库
    luaL_openlibs(L);

    // 重定向 Lua 打印函数到自定义的 luaPrint 函数
    lua_register(L, "print", luaPrint);
    lua_register(L, "func", myVarArgFunction);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::runLuaScript(lua_State *L, const char *script)
{
    // 加载 Lua 脚本文件
    if (luaL_loadfile(L, script) != LUA_OK)
    {

        ui->plainTextEditOutput->appendPlainText("Failed to load script: " + QString(lua_tostring(L, -1)));

        lua_pop(L, 1); // 移除错误消息
        return;
    }

    // 保护模式调用 Lua 脚本
    if (lua_pcall(L, 0, 0, 0) != LUA_OK)
    {

        ui->plainTextEditOutput->appendPlainText("Failed to run script: " + QString(lua_tostring(L, -1)));

        lua_pop(L, 1); // 移除错误消息
        return;
    }
}


void MainWindow::on_pushButtonRun_clicked()
{
    QString fileName = QFileDialog::getOpenFileName(this, "Open Lua Script", "", "Lua Scripts (*.lua)");
    if (!fileName.isEmpty()) {
        QByteArray byteArray = fileName.toUtf8();
        const char* cstr = byteArray.constData(); // 获取 const char* 类型的 C 风格字符串
        runLuaScript(L, cstr);
    }
}

